from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List

from ..database import get_db
from ..models import User, Role
from ..schemas import Role as RoleSchema, RoleCreate, RoleWithUsers
from ..auth import get_current_active_user

router = APIRouter(prefix="/api/chance/roles", tags=["roles"])

# 获取角色列表
@router.get("/", response_model=List[RoleSchema])
async def get_roles(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    roles = db.query(Role).offset(skip).limit(limit).all()
    return roles

# 获取单个角色
@router.get("/{role_id}", response_model=RoleWithUsers)
async def get_role(
    role_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    role = db.query(Role).filter(Role.id == role_id).first()
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")
    return role

# 创建角色
@router.post("/", response_model=RoleSchema)
async def create_role(
    role: RoleCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 检查角色名是否已存在
    db_role = db.query(Role).filter(Role.name == role.name).first()
    if db_role:
        raise HTTPException(status_code=400, detail="角色名已存在")
    
    # 创建新角色
    db_role = Role(name=role.name)
    db.add(db_role)
    db.commit()
    db.refresh(db_role)
    return db_role

# 关联用户到角色
@router.post("/{role_id}/users/{user_id}")
async def associate_user_to_role(
    role_id: int,
    user_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 查找角色和用户
    role = db.query(Role).filter(Role.id == role_id).first()
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 关联用户到角色
    if user not in role.users:
        role.users.append(user)
        db.commit()
    
    return {"message": "用户已成功关联到角色"}

# 从角色中移除用户
@router.delete("/{role_id}/users/{user_id}")
async def remove_user_from_role(
    role_id: int,
    user_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    # 查找角色和用户
    role = db.query(Role).filter(Role.id == role_id).first()
    if not role:
        raise HTTPException(status_code=404, detail="角色不存在")
    
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 从角色中移除用户
    if user in role.users:
        role.users.remove(user)
        db.commit()
    
    return {"message": "用户已成功从角色中移除"}